import axios from 'axios'

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8090/api'

// 创建axios实例
const api = axios.create({
    baseURL: API_URL,
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器
api.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('auth_token')
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 响应拦截器
api.interceptors.response.use(
    (response) => {
        return response
    },
    (error) => {
        if (error.response?.status === 401) {
            // 清除本地存储的认证信息
            localStorage.removeItem('auth_token')
            localStorage.removeItem('auth_user')
        }
        return Promise.reject(error)
    }
)

export default {
    // 获取考试信息
    getExam(examId) {
        return api.get(`/exams/${examId}`)
    },

    // 开始考试
    startExam(examId) {
        return api.post(`/exams/${examId}/start`)
    },

    // 获取考试题目
    getExamQuestions(examId) {
        return api.get(`/exams/${examId}/questions`)
    },

    // 提交答案
    submitAnswer(examRecordId, questionId, answer) {
        return api.post(`/exam-records/${examRecordId}/answers`, {
            question_id: questionId,
            answer: answer
        })
    },

    // 提交考试
    submitExam(examRecordId) {
        return api.post(`/exam-records/${examRecordId}/submit`)
    },

    // 保存草稿
    saveDraft(examRecordId) {
        return api.post(`/exam-records/${examRecordId}/save-draft`)
    }
}
